<template>
  <Container class="single-sale sale-detail">
    <div slot="header" class="container-header title title-center">{{ title }}
      <Button size="large" class="fl btn-back" icon="ios-arrow-back" @click="$router.back()">返回</Button>
      <export-btn v-if="type === 'FACTORY_ACTIVITY'" class="fr ml" @onExport="onUpImport"></export-btn>
      <div v-if="form.activityInfoDTO && form.activityInfoDTO.checkStatusEnum === 'UNCHECKED'" class="fr">
        <Button size="large" class="btn-back" type="primary" @click="onAudit(1)">通过</Button>
        <Button size="large" class="btn-back" @click="onAudit(2)">驳回</Button>
      </div>
    </div>
    <DefaultDetailItem :type="activeType" :form="form" />
    <MainProductItem v-if="showMain && type !== 'FACTORY_ACTIVITY'" :type="type" :bargain-coupons-data="bargainCouponsData" />
    <GiftProductItem v-if="showGift" :list="giftList" />
    <BargainProductItem v-if="type == 'FACTORY_ACTIVITY'" :list="bargainList" />
    <Loader :status="status" @refresh="getData" />
  </Container>
</template>
<script>
import { formatCurrency, preFixPath } from '@/util'
import { mapGetters } from 'vuex'
import DefaultDetailItem from './detail/DefaultDetailItem'
import BargainProductItem from './detail/BargainProductItem'
import GiftProductItem from './detail/GiftProductItem'
import MainProductItem from './detail/MainProductItem'
export default {
  components: {
    DefaultDetailItem,
    GiftProductItem,
    MainProductItem,
    BargainProductItem
  },
  data () {
    return {
      id: this.$route.query.id || '',
      type: this.$route.query.type || '',
      preFixPath,
      activeType: null,
      status: 'pass',
      title: '',
      showGift: false,
      showMain: false,
      form: {},
      mainList: [],
      giftList: [],
      bargainList: []
    }
  },
  mounted () {
    if (this.id && this.type) this.getData()
    this.$store.dispatch('getStoreType')
  },
  methods: {
    getData () {
      let url = ''
      let type = ''
      switch (this.type) {
        // 满减送
        case 'FULL_CUT_GIFT':
          this.activeType = 1
          url = '/activity/full_cut_gift/detail/'
          type = 'activityFullCutGiftDTO'
          break
        // 满赠
        case 'FULL_GIFT':
          this.activeType = 2
          url = '/activity/full_gift/detail/'
          type = 'activityFullGiftDTO'
          break
        // 单品
        case 'SINGLE':
          this.activeType = 3
          url = '/activity/single/detail/'
          type = 'activitySingleDTO'
          break
        // 赠品
        case 'GIFT':
          this.activeType = 4
          url = '/activity/gift/detail/'
          type = 'activityGiftDTO'
          break
        // 满减
        case 'FULL_CUT':
          this.activeType = 5
          url = '/activity/full_cut/detail/'
          type = 'activityFullCutDTO'
          break
        // 多买优惠
        case 'BUY_MORE':
          this.activeType = 6
          url = '/activity/buy_more/detail/'
          type = 'activityBuyMoreDTO'
          break
        // 满额返券
        case 'FULL_COUPON':
          this.activeType = 7
          url = '/activity/full_gift_coupon/detail/'
          type = 'activityFullGiftCouponDTO'
          break
        // 工厂促销
        case 'FACTORY_ACTIVITY':
          this.activeType = 8
          url = '/activity/factory_info/detail/'
          type = 'activityFactoryInfoDTO'
          break
      }
      this.status = 'loading'
      this.$store.dispatch('getGiftCouponList').then(res => {
        res.forEach(item => {
          this.$store.state.fullReturnSale.FullreturnForm.giftCoupon[item.id] = item.couponName
        })
        this.getDetail(url, type)
      })
    },
    getDetail (url, type) {
      this.$ajaxGet(url + `${this.id}`).then(data => {
        let str = ''
        let userLevel = []
        this.title = data.activityName
        userLevel = data.promotionMemberScope && data.promotionMemberScope.split(',')
        this.storeTypeData.forEach(item => {
          userLevel && userLevel.forEach(level => {
            if (item.id === level) str += item.text + '  '
          })
        })
        // 如果是满额
        let couponList = []
        if (this.activeType == 7 && data.activityFullGiftCouponDTO.fullGiftCouponTypeEnum !== 'PRODUCT') {
          couponList = data.activityFullGiftCouponDTO.giftCouponRuleList.map(item => {
            return {
              value: item.m,
              isParcel: item.isParcel,
              denomination: 'custom',
              useCondition: '',
              validityDays: '',
              custom: ''
            }
          })
          this.$jsonPost(`/coupon/coupon_info/ids`, data.activityFullGiftCouponDTO.giftCouponIdList).then(res => {
            couponList.forEach((item, index) => {
              res.forEach((todo, index1) => {
                if (index == index1) {
                  item.denomination = 'custom'
                  item.useCondition = todo.useCondition
                  item.validityDays = todo.validityDays
                  item.custom = todo.denomination
                }
              })
            })
            this.form = data
            this.form.couponList = couponList
          })
        } else {
          this.form = data
        }
        this.form.promotionMemberScope = str
        // 如果参与方式不是全场，就要去调用商品接口
        if (data.joinTypeEnum !== 'WHOLE') {
          if (this.activeType !== 7) { // 不是满额返券的请求
            this.getProduct(data[type].activityId)
          }
          this.showMain = true
        } else {
          this.showMain = false
        }
        // 如果是满赠，赠品促销，满减（isGiftProduct为true）则去加载赠品列表
        if (this.activeType === 2 || this.activeType === 4 || (this.activeType === 1 && data.activityFullCutGiftDTO.isGiftProduct)) {
          this.showGift = true
          this.getGift(data[type].activityId)
        } else {
          this.showGift = false
        }
        this.status = 'pass'
      })
    },
    getProduct (id) {
      this.status = 'loading'
      this.$ajaxGet(`/activity/activity_sku_list/${id}`).then(data => {
        if (this.type == 'FACTORY_ACTIVITY') {
          this.bargainList = data
        }
        this.mainList = (data || []).map(item => {
          let target = {
            code: item.productSn,
            skuCode: '-',
            name: item.title,
            img: preFixPath + item.productPrimaryImg,
            marketPrice: '[' + item.minMarketingPrice + '~' + item.maxMarketingPrice + ']',
            showChildren: false,
            children: (item.item || []).map(child => {
              let childTarget = {
                code: child.productSn,
                skuCode: child.productSkuInfo.skuSn,
                name: child.productSkuInfo.title,
                img: preFixPath + child.productSkuInfo.productPrimaryImg,
                marketPrice: child.productSkuInfo.salePrice
              }
              if (this.activeType === 3) {
                childTarget.promotionPrice = formatCurrency(child.promotionPrice, true)
              } else {
                childTarget.promotionPrice = '--'
              }
              if (this.activeType === 8) {
                childTarget.activityFactoryGiftDTO = child.activityFactoryGiftDTO
                childTarget.sellOutQuantity = child.sellOutQuantity
                childTarget.promotionPrice = child.promotionPrice
              }
              return childTarget
            })
          }
          if (this.activeType === 3) {
            target.promotionPrice = '[' + item.minPromotionPrice + '~' + item.maxPromotionPrice + ']'
          } else {
            target.promotionPrice = '--'
          }
          return target
        })
        this.status = 'pass'
      }).catch(() => {
        this.status = 'error'
      })
    },
    getGift (id) {
      this.status = 'loading'
      this.$ajaxGet(`/activity/activity_gift_sku_list/${id}`).then(data => {
        (data || []).forEach(item => {
          (item || []).forEach(obj => {
            obj.code = obj.productSn
            obj.skuCode = '--'
            obj.name = obj.title
            obj.img = preFixPath + obj.productPrimaryImg
            obj.price = '[' + obj.minReturnPrice ? obj.minReturnPrice : '--' + '~' + obj.maxReturnPrice ? obj.maxReturnPrice : '--' + ']'
            obj.showChildren = false
            obj.children = (obj.item || []).map(child => {
              // if(child.productSkuInfo) {
              return {
                skuCode: child.productSkuInfo.skuSn,
                code: child.productSn,
                name: child.productSkuInfo.title,
                img: preFixPath + child.productSkuInfo.productPrimaryImg,
                price: child.returnPrice
              }
              // }
            })
          })
        })
        this.giftList = data
      })
    },
    onAudit (type) {
      let param = {
        activityId: this.id,
        checkStatusEnum: type === 1 ? 'PASS' : 'REJECT'
      }
      this.$ajaxPost('/activity/check', param).then(() => {
        this.$Notice.success({
          title: '操作成功'
        })
        this.getData()
      })
    },
    onUpImport () {
      this.$ajaxGet('/activity/sku/export', { activityId: this.form.activityFactoryInfoDTO.activityId }).then(data => {
        this.$router.push({ name: 'home/export/list' })
      })
    }
  },
  computed: {
    ...mapGetters(['storeTypeData'])
  }
}
</script>

